﻿namespace DatabaseDoc.Library.Factories
{
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    /// <summary>
    /// Outputter factory
    /// </summary>
    public class OutputterFactory
    {
        /// <summary>
        /// The collection of outputters
        /// </summary>
        [ImportMany(typeof(IOutputter))]
        private IEnumerable<IOutputter> outputters;

        /// <summary>
        /// Initializes a new instance of the <see cref="OutputterFactory"/> class.
        /// </summary>
        public OutputterFactory()
        {
            var catalog = new DirectoryCatalog(".", "*");
            
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

        /// <summary>
        /// Creates the outputter.
        /// </summary>
        /// <param name="outputterKeyName">Name of the outputter key.</param>
        /// <returns>The outputter</returns>
        public IOutputter CreateOutputter(string outputterKeyName)
        {
            if (this.outputters == null)
            {
                return null;
            }

            var outputter = this.outputters.SingleOrDefault(o => string.Compare(o.Key, outputterKeyName, true) == 0);
            return outputter;
        }
    }
}